import type { FC, ReactNode } from 'react'
import React, { memo, useState } from 'react'
import Upload, { RcFile } from 'antd/es/upload'
import { message } from 'antd'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import { REAL_BASE_URL } from '@/service/config'
import { reqUploadFile } from '@/service/module/app'

interface IProps {
  children?: ReactNode
  getFileUrl?: (url: string) => void
  imgUrl?: string
}

const beforeUpload = (file: RcFile) => {
  const fileTypes = ['image/jpeg', 'image/png', 'image/jpg']
  const result = fileTypes.includes(file.type)
  if (!result) {
    message.error('你只能上传 JPG/JPEG/PNG 图片类型~')
  }
  const isLt2M = file.size / 1024 / 1024 < 3
  if (!isLt2M) {
    message.error('图片只能小于3MB哦~')
  }
  return result && isLt2M
}
const UploadImg: FC<IProps> = (props) => {
  const [loading, setLoading] = useState(false)
  const [imageUrl, setImageUrl] = useState<string>()

  async function handleUploadImg({ file }: any) {
    //设置图片上传的参数
    const formData = new FormData()
    formData.append('file', file)
    const res = await reqUploadFile(formData)
    const url = REAL_BASE_URL + res.data
    setImageUrl(url)
    props.getFileUrl?.(url)
    setLoading(false)
  }

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>upload</div>
    </div>
  )
  return (
    <Upload
      name="avatar"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      beforeUpload={beforeUpload}
      customRequest={handleUploadImg}
    >
      {imageUrl || props.imgUrl ? (
        <img
          src={imageUrl ?? props.imgUrl}
          alt="avatar"
          style={{ width: '100%' }}
        />
      ) : (
        uploadButton
      )}
    </Upload>
  )
}

export default memo(UploadImg)
